package com.qc31.baselib.utils

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import java.io.*
import java.text.DecimalFormat

/**
 *@Author Jasper
 *@Time   2020/9/29
 *@Desc   todo
 */
object FileUtil {
    /**
     * 转换文件大小
     *
     * @param size
     * @return
     */
    private val df = DecimalFormat("#.00")
    fun formatFileSize(size: Long): String {
        var fileSizeString = ""
        val wrongSize = "0B"
        if (size == 0L) {
            return wrongSize
        }
        fileSizeString = when {
            size < 1024 -> {
                df.format(size.toDouble()) + "B"
            }
            size < 1048576 -> {
                df.format(size.toDouble() / 1024) + "KB"
            }
            size < 1073741824 -> {
                df.format(size.toDouble() / 1048576) + "MB"
            }
            else -> {
                df.format(size.toDouble() / 1073741824) + "GB"
            }
        }
        return fileSizeString
    }


    fun saveBitmap(bitmap: Bitmap, fileName: String) {
        val bitmap2Bytes = bitmap2Bytes(bitmap)
        CacheMMKV.encodeSave(fileName, bitmap2Bytes)
    }

    private fun bitmap2Bytes(bitmap: Bitmap): ByteArray {
        val boStream = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, boStream)
        return boStream.toByteArray()
    }

    fun bytes2Bitmap(fileName: String): Bitmap? {
        val bytes = CacheMMKV.decodeByteArraySave(fileName) ?: return null
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
    }

}